import React, { useState } from "react";
import { connect } from "react-redux";
import { Form, message, notification } from "antd";
import { withRouter } from "react-router-dom";
import { register } from "utils/api/userApi";
import RegisterDom from "./registerDom";

const Register = props => {
  const { form, history } = props;
  let [confirmDirty, setConfirmDirty] = useState(false);

  const handleConfirmBlur = e => {
    const { value } = e.target;
    setConfirmDirty(confirmDirty || !!value);
  };

  const compareToFirstPassword = (rule, value, callback) => {
    if (value && value !== form.getFieldValue("password")) {
      callback("两次输入的密码不一致!");
    } else {
      callback();
    }
  };

  const validateToNextPassword = (rule, value, callback) => {
    if (value && confirmDirty) {
      form.validateFields(["confirm"], { force: true });
    }
    callback();
  };

  const handleSubmit = e => {
    e.preventDefault();
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        register(values)
          .then(res => {
            const { err, msg } = res;
            if (err === 0) {
              notification.success({
                message: "注册成功",
                description: "即将为您跳转登录页面。",
                duration: 1,
                onClose: () => {
                  history.push("/login");
                }
              });
            } else {
              message.error(msg, 2);
            }
          })
          .catch(err => {
            console.log(err);
          });
      }
    });
  };

  return (
    <RegisterDom
      handleSubmit={handleSubmit}
      form={form}
      handleConfirmBlur={handleConfirmBlur}
      compareToFirstPassword={compareToFirstPassword}
      validateToNextPassword={validateToNextPassword}
    />
  );
};

const RegisterWrap = Form.create({ name: "vision_login" })(Register);
export default connect(store => ({}), {
  
})(withRouter(RegisterWrap));
